package cn.shengchao.examstarvideo.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.shengchao.examstarvideo.config.Res;
import cn.shengchao.examstarvideo.config.idempotent.annotation.Idempotent;
import cn.shengchao.examstarvideo.service.VideoService;
import cn.shengchao.examstarvideo.util.GanKaoHttpUtil;
import cn.shengchao.examstarvideo.util.HttpKit;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.continew.starter.cache.redisson.util.RedisUtils;
import top.continew.starter.log.annotation.Log;

import java.io.IOException;
import java.net.URLDecoder;
import java.time.Duration;
import java.util.concurrent.ExecutionException;

@RestController
@RequestMapping("/storage")
public class VideoController {

    @Autowired
    private VideoService videoService;

    /**
     * 播放视频
     * :definition:清晰度
     * 参考类：PlayInfo
     */
    @GetMapping(value = "/video/cdn/auth")
    @Idempotent
    @SaIgnore
    @Log(ignore = true)
    public Res auth() {
        try{
            StpUtil.checkLogin();;
        }catch (Exception e){
            HttpKit.getResponse().setStatus(401);
            throw new NotLoginException("", "", "");
        }
        String key = HttpKit.getRequest().getParameter("auth");
        if (key == null) {
            HttpKit.getResponse().setStatus(401);
            throw new NotLoginException("", "", "");
        }
        String value = RedisUtils.get(key);
        if (StrUtil.isNotBlank(value)) {
            RedisUtils.delete(key);
            return Res.ok();
        }
        HttpKit.getResponse().setStatus(401);
        throw new NotLoginException("", "", "");
    }

    /**
     * 播放视频
     * :definition:清晰度
     * 参考类：PlayInfo
     */
    @RequestMapping(value = "/video/{appName}/{videoId}.{videoType}")
    @Idempotent(timeout = 100)
    @Log(value = "播放视频", module = "播放视频")
    public void videoFile(@PathVariable(value = "appName") String appName,
                          @PathVariable(value = "videoId") String videoId,
                          @RequestParam(required = false, defaultValue = "FD") String definition,
                          @PathVariable(value = "videoType") String videoType
    ) throws IOException, ExecutionException, InterruptedException, ClientException {
        if (("gankao".equals(appName)&&StrUtil.isNotBlank(videoId)&&videoId.contains("@"))){
            String uid =StpUtil.getLoginIdAsString();
            String[] videoIdArr = videoId.split("@");
            String errorUrl="http://store.91yunshi.com/unknown";
            if (NumberUtil.isInteger(videoIdArr[0])&&NumberUtil.isInteger(videoIdArr[0])){
                String url = GanKaoHttpUtil.requestGetPlayVideoResourceForWeb(uid ,Integer.parseInt(videoIdArr[1]),Integer.parseInt(videoIdArr[0]));
                if (StrUtil.isNotBlank( url)){
                    HttpKit.getResponse().setHeader("Content-Type", "application/x-mpegurl");
                    HttpKit.getResponse().sendRedirect(url);
                    return;
                }
            }
            HttpKit.getResponse().setHeader("Content-Type", "application/text-html");
            HttpKit.getResponse().getWriter().write(errorUrl);
            return;
        }
        HttpKit.getResponse().setHeader("Content-Type", "application/x-mpegurl");
        HttpKit.getResponse().sendRedirect(videoService.videoFile(videoId.split("\\.")[0], definition, videoType));
    }

    /**
     * 获取视频上传凭证
     *
     * @param fileName  文件名
     * @param title     标题
     * @param extension 扩展名
     * @param size      文件大小
     */
    @Log(value = "获取上传凭证", module = "获取上传凭证")
    @SaIgnore
    @GetMapping(value = "/video/auth")
    public CreateUploadVideoResponse getVideoUploadAuth(@RequestParam String fileName,
                                                        @RequestParam String title,
                                                        @RequestParam String extension,
                                                        @RequestParam Long size
    ) throws ClientException {
        return videoService.getVideoUploadAuth(title, fileName, extension, size);
    }

    /**
     * 获取视频上传凭证
     */
    @Log(value = "刷新上传凭证", module = "刷新上传凭证")
    @SaIgnore
    @GetMapping(value = "/video/auth/refresh")
    public RefreshUploadVideoResponse refreshVideoPlayAuth(@RequestParam String videoId
    ) throws ClientException, ExecutionException, InterruptedException {
        return videoService.refreshVideoPlayAuth(videoId);
    }
}
